﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Transitionals;
using ViewLED.UI;

namespace ViewLED
{
    /// <summary>
    /// Screen.xaml 的交互逻辑
    /// </summary>
    public partial class Screen : Window
    {
        /// <summary>
        /// 公共所需
        /// </summary>
        ArrayList list = new ArrayList();
        int[] switchTime = new int[7]{1,2,3,5,7,10,20};
        DispatcherTimer timer = null;
        private ObservableCollection<Type> transitionTypes = new ObservableCollection<Type>();
        int s = 0;

        private void showError()
        {
            MessageBox.Show("未找到播放列表！", "错误提示");
        }

        // 随机选择一种切换特效
        void selTrans()
        {
            int m_nIndex = 0;
            m_nIndex = new Random().Next(0, transitionTypes.Count);
            Type transitionType = transitionTypes[m_nIndex];
            Transition t = (Transition)Activator.CreateInstance(transitionType);
            mainp.Transition = t;
        }

        public void LoadTransitions(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                if (transitionTypes.Contains(type)) { continue; }

                if ((typeof(Transition).IsAssignableFrom(type)) && (!type.IsAbstract))
                {
                    transitionTypes.Add(type);
                }
            }
        }

        /// <summary>
        /// 文字播放所需
        /// </summary>
        Storyboard story = new Storyboard();

        public void setAutoChangeTxt()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(switchTime[int.Parse(ConfigurationManager.AppSettings["SwitchTime"])]);
            timer.Tick += new EventHandler(txtTimer_Tick);
            timer.Start();
        }

        private void txtTimer_Tick(object sender, EventArgs e)
        {
            timer.Interval = TimeSpan.FromSeconds(switchTime[int.Parse(ConfigurationManager.AppSettings["SwitchTime"])]);
            s = (s + 1) % list.Count;
            TextRange docTextRange = new TextRange(richTxt.Document.ContentStart, richTxt.Document.ContentEnd);
            using (FileStream fs = File.Open(list[s].ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
            {
                docTextRange.Load(fs, System.Windows.DataFormats.Rtf);
                story = (Storyboard)this.FindResource(Model.ScreenManager.randomAnimation());
                story.Begin(this);
                fs.Dispose();
                fs.Close();
                GC.Collect();
            }
        }

        /// <summary>
        /// 图片播放所需
        /// </summary>      
        bool which = true;  //记录当前显示的A或B
        UI.ImgEle iA = new ImgEle();
        UI.ImgEle iB = new ImgEle();

        public void setAutoChangeImg()
        {
            // 设置自动切换计时器
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(switchTime[int.Parse(ConfigurationManager.AppSettings["SwitchTime"])]);
            timer.Tick += new EventHandler(imageTimer_Tick);
            timer.Start();
        }

        private void imageTimer_Tick(object sender, EventArgs e)
        {
            if (timer != null)
                timer.Interval = TimeSpan.FromSeconds(switchTime[int.Parse(ConfigurationManager.AppSettings["SwitchTime"])]);
            selTrans();
            GC.Collect();
            if (which)
            {
                Uri uri = new Uri(list[s % list.Count].ToString(), UriKind.Absolute);
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = uri;
                image.EndInit();
                iB.Img = image;
                iB.StretchType = int.Parse(ConfigurationManager.AppSettings["ImageStretchMode"]);
                mainp.Content = iB;
                which = false;
            }
            else
            {
                Uri uri = new Uri(list[s % list.Count].ToString(), UriKind.Absolute);
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = uri;
                image.EndInit();
                iA.Img = image;
                iA.StretchType = int.Parse(ConfigurationManager.AppSettings["ImageStretchMode"]);
                mainp.Content = iA;
                which = true;
            }
            s = (s + 1) % list.Count;
        }

        /// <summary>
        /// 视频播放所需
        /// </summary>
        UI.VideoEle v = new VideoEle();

        public void setAutoChangeVideo()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Tick += new EventHandler(videoTimer_Tick);
            timer.Start();
        }

        private void videoTimer_Tick(object sender, EventArgs e)
        {
            if (!v.isPlaying && list.Count > 0)
            {
                v.isPlaying = true;
                selTrans();
                s = (s + 1) % list.Count;
                v.mediaVideo.Source = new Uri(list[s].ToString(), UriKind.Absolute);
                v.StretchType = int.Parse(ConfigurationManager.AppSettings["VideoStretchMode"]);
                v.mediaVideo.Play();
                mainp.Content = v;
            }
        }


        public Screen()
        {
            InitializeComponent();
            // 从App.config中读取参数信息
            Left = double.Parse(ConfigurationManager.AppSettings["ScreenPosLeft"]);
            Top = double.Parse(ConfigurationManager.AppSettings["ScreenPosTop"]);
            Width = double.Parse(ConfigurationManager.AppSettings["ScreenWidth"]);
            Height = double.Parse(ConfigurationManager.AppSettings["ScreenHeight"]);
            // 置顶显示屏幕
            Topmost = true;
            // 加载特效
            LoadTransitions(Assembly.GetAssembly(typeof(Transition)));
        }

        public void playText()
        {
            list = Model.FileExplorer.listFile("Text", true);
            if (list.Count > 0)
            {
                TextRange docTextRange = new TextRange(richTxt.Document.ContentStart, richTxt.Document.ContentEnd);
                using (FileStream fs = File.Open(list[0].ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
                {
                    docTextRange.Load(fs, System.Windows.DataFormats.Rtf);
                    fs.Dispose();
                    fs.Close();
                    GC.Collect();
                }
                setAutoChangeTxt();
            }
            else
            {
                showError();
                return;
            }
            scr0.Visibility = System.Windows.Visibility.Visible;
        }

        public void playPicture()
        {
            list = Model.FileExplorer.listFile("Picture", true);
            if (list.Count < 0)
            {
                showError();
                return;
            }
            setAutoChangeImg();
            scr1.Visibility = System.Windows.Visibility.Visible;
        }

        public void playVideo()
        {
            s--;
            list = Model.FileExplorer.listFile("Video", true);
            if (list.Count == 0)
            {
                showError();
                return;
            }
            setAutoChangeVideo();
            scr1.Visibility = System.Windows.Visibility.Visible;
        }
    } 
}
